/*
*  Copyright (C) 2009  Peter Kist & Jan Ripke
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation, either version 3 of the License, or
*  (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "Database.h"

namespace galaxy {
	namespace database {

		bool Database::serverInitialized = false;


		Database::Database(void)
		{
			mysql = 0L;
			connected = false;
		}

		Database::Database(std::string& database, std::string& cfgFile)
		{
			mysql = 0L;
			connected = false;

			initialize (database, cfgFile);
		}


		Database::~Database(void)
		{
			if (mysql) {
				mysql_close(mysql);
				connected = false;
			}

			if (serverInitialized == true) {
				mysql_server_end();
				serverInitialized = false;
			}
		}


		bool Database::initialize(std::string& database, std::string& cfgFile) 
		{
			if (serverInitialized == false) {
				std::string defaultsFile ("--defaults-file=");
				defaultsFile.append (cfgFile);

				char * server_options[] = { (char *) database.c_str(), (char *) defaultsFile.c_str() };
				char * server_groups[]  = {"libmysqd_server", "libmysqd_client", (char *) 0L};

				/* connect to database */
				if (mysql_library_init(sizeof(server_options) / sizeof (char *), server_options, server_groups) != 0) {
					return false;
				}

				serverInitialized = true;
			}

			return true;
		}

		bool Database::open (std::string& dbName) {

			if (! connected) {
				mysql = mysql_init(0L);
				if (! mysql) {
					return false;
				}

				mysql_options(mysql, MYSQL_READ_DEFAULT_GROUP, "libmysqld_client");
				mysql_options(mysql, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL);

				if (! mysql_real_connect(mysql, NULL,NULL,NULL, dbName.c_str(), 0,NULL,0)) {
					return false;
				}

				connected = true;
			}
			return true;
		}

		bool Database::close () {
			if (connected) {
				mysql_close(mysql);
				connected = false;
			}

			return true;
		}


		const char * Database::lastError () {
			if (mysql) {
				return mysql_error (mysql);
			}
			return "not connected or initialized";
		}

	} // namespace database
} // namespace galaxy
